import BTComposite from '../../Base/BTComposite'
import { NodeStatus } from '../../Enum'

export default class CompositeParallel extends BTComposite {
  executionStatus: NodeStatus[] = []

  get status() {
    let childrenComplete = true
    for (let i = 0; i < this.executionStatus.length; i++) {
      if (this.executionStatus[i] === NodeStatus.Running) {
        childrenComplete = false
      } else if ((this.executionStatus[i] = NodeStatus.Failure)) {
        return NodeStatus.Failure
      }
    }
    return childrenComplete ? NodeStatus.Success : NodeStatus.Running
  }

  set status(_) {}

  onStart() {
    super.onStart()
    this.index = 0
    this.executionStatus = new Array(this.childrens.length).fill(NodeStatus.Inactive)
  }

  canExecute(): boolean {
    return this.index < this.childrens.length
  }

  onChildExecuted(status: NodeStatus, index: number): void {
    this.executionStatus[index] = status
  }

  onConditionalAbort(_index: number) {
    this.index = 0
    this.executionStatus = new Array(this.childrens.length).fill(NodeStatus.Inactive)
  }

  canRunParallelChildren(): boolean {
    return true
  }

  onChildStart() {
    this.executionStatus[this.index] = NodeStatus.Running
    this.index++
  }
}
